<template>
  <div class="contract-config">
    <!--  合同类型 start  -->
    <div class="contract-config-tabs">
      <a-tabs :active-key="activeTabKey" @tab-click="handelTabClick">
        <a-tab-pane v-for="(item, index) in contractTypes" :key="item.contractTypeId">
          <template #title>
            <span style="margin-right: 12px">{{ item.contractTypeName }}</span>
            <icon-close @click.stop="handelDelType(item, index)" />
          </template>
        </a-tab-pane>
      </a-tabs>
      <a-button type="text" @click="handelAddType">
        <template #icon>
          <icon-plus />
        </template>
        新建合同类型
      </a-button>
    </div>
    <!--  合同类型 end  -->
    <!-- 签约方式 start -->
    <div class="signing-method" v-if="contractTypes.length > 0">
      <div class="signing-name">签约方式：{{ signingMethod === 1 ? "纸质" : signingMethod === 2 ? "电子" : "电子或纸质" }}</div>
      <div class="signing-name" v-if="isVerify != null">核量：{{ isVerify === 1 ? "人工确认" : "自动确认" }}</div>
      <div class="signing-name" v-if="precondition === 1">进行核量条件：合同签约后</div>
      <div class="signing-name" v-if="precondition === 2">进行核量条件：满足收款比例{{ paymentRatio }}%</div>
    </div>
    <!-- 签约方式 end -->
    <!--  合同配置 start  -->
    <div class="app-container contract-config-body">
      <!--    报价模板 start  -->
      <div class="template-item">
        <div class="template-item-header">关联报价模板</div>
        <div class="template-item-content">
          <img src="@/assets/images/contract-config-icon.png" />
          <template v-if="offerTemplateList.length">
            <div class="quotation-template-list">
              <div class="quotation-template-item" v-for="item in offerTemplateList" :key="item.offerId">
                {{ item.budgetName }}
              </div>
            </div>
            <div class="template-list-button">
              <a-button type="primary">报价模板管理</a-button>
            </div>
          </template>
          <CustomEmpty v-else>
            <template #default>
              <div class="template-list-button">
                <a-button type="primary">报价模板管理</a-button>
              </div>
            </template>
          </CustomEmpty>
        </div>
      </div>
      <!--    报价模板 end  -->

      <!--    协议模板 start  -->
      <div class="template-item">
        <div class="template-item-header">关联协议模板</div>
        <div class="template-item-content">
          <img src="@/assets/images/contract-config-icon.png" />
          <template v-if="protocolTemplateList.length">
            <div class="agreement-template-list">
              <div class="agreement-template-item" v-for="item in protocolTemplateList" :key="item.protocolId">
                <div class="label" v-ellipsis="{ rows: 1, text: item.templateName }"></div>
                <GiSvgIcon name="rectification-del" size="16" @click="handelDelProtocol(item.protocolId)" />
              </div>
            </div>
            <div class="template-list-button">
              <a-button type="primary" @click="handelAddProtocol">去添加</a-button>
            </div>
          </template>
          <CustomEmpty v-else>
            <template #default>
              <div class="template-list-button">
                <a-button type="primary" @click="handelAddProtocol">去添加</a-button>
              </div>
            </template>
          </CustomEmpty>
        </div>
      </div>
      <!--    协议模板 end  -->

      <!--    收款计划 start  -->
      <div class="template-item">
        <div class="template-item-header">收款计划</div>
        <div class="template-item-content">
          <img src="@/assets/images/contract-config-icon.png" />
          <template v-if="receiveBusTypeList.length">
            <div class="plan-template-list">
              <div class="plan-template-item" v-for="item in receiveBusTypeList" :key="item.receiveBusTypeId">
                <div class="template-item-label">{{ item.receiveBusTypeName }}</div>
                <a-table
                  :data="item.nodeList"
                  :columns="nodeColumns as any"
                  :pagination="false"
                  :stripe="true"
                  :scroll="{ y: '100%' }"
                >
                  <template #receiveTaskName="{ record }">
                    <a-tooltip :content="record.receiveTaskName">
                      <div class="ellipsis" style="font-size: 14px; margin-bottom: 10px">{{ record.receiveTaskName }}</div>
                    </a-tooltip>
                    <div v-show="!record.status" style="font-size: 12px; color: #ff3333">已失效</div>
                  </template>
                  <template #checkName="{ record }">
                    <div v-if="record.checkName">{{ record.checkName }}</div>
                    <div v-else>--</div>
                  </template>
                  <template #receiveTaskScale="{ record }">
                    <div>{{ record.receiveTaskScale }}%</div>
                  </template>
                </a-table>
              </div>
            </div>
            <div class="template-list-button">
              <a-button type="primary" @click="handelShowPaymentPlan">去设置</a-button>
            </div>
          </template>
          <CustomEmpty v-else>
            <template #default>
              <div class="template-list-button">
                <a-button type="primary" @click="handelShowPaymentPlan">去设置</a-button>
              </div>
            </template>
          </CustomEmpty>
        </div>
      </div>
      <!--    收款计划 end  -->
    </div>
    <!--  合同配置 end  -->

    <!--  TODO:后续优化，可以封装通用弹窗  -->
    <!--  新建合同类型弹窗 start  -->
    <a-modal :visible="isShowAddModal" width="486px" unmount-on-close :mask-closable="false" :closable="false">
      <CustomTitle title="新增合同类型" />
      <div class="add-modal-form">
        <a-form :model="modalForm" :rules="modalFormRules" auto-label-width ref="modalFormRef">
          <a-form-item field="contractTypeName" label="合同类型名称">
            <a-input placeholder="请输入合同类型名称" v-model.trim="modalForm.contractTypeName" allow-clear />
          </a-form-item>
          <a-form-item field="signingMethod" label="签约方式">
            <a-radio-group v-model="modalForm.signingMethod">
              <a-radio :value="1">纸质</a-radio>
              <a-radio :value="2">电子</a-radio>
              <a-radio :value="3">电子或纸质</a-radio>
            </a-radio-group>
          </a-form-item>
          <a-form-item field="isVerify" label="核量">
            <a-radio-group v-model="modalForm.isVerify">
              <a-radio :value="1">人工确认</a-radio>
              <a-radio :value="0">自动确认</a-radio>
            </a-radio-group>
          </a-form-item>
          <a-form-item field="precondition" label="进行核量的条件">
            <a-radio-group
              v-model="modalForm.precondition"
              @change="
                value => {
                  value === 1;
                  modalForm.paymentRatio = null;
                }
              "
            >
              <a-radio :value="1">合同签约后</a-radio>
              <a-radio :value="2">满足收款比例</a-radio>
            </a-radio-group>
          </a-form-item>
          <a-form-item field="paymentRatio" label="收款比例" v-if="modalForm.precondition === 2">
            <a-input placeholder="请输入收款比例" v-model.trim="modalForm.paymentRatio" allow-clear type="number">
              <template #append> %</template>
            </a-input>
          </a-form-item>
        </a-form>
      </div>
      <template #footer>
        <a-button style="width: 92px; background-color: #f2f3f5" @click="handleAddModalCancel">取消</a-button>
        <a-button style="width: 92px" type="primary" @click="handleAddModalOk">确定</a-button>
      </template>
    </a-modal>
    <!--  新建合同类型弹窗 end  -->

    <!--  TODO:后续优化，可以封装通用删除弹窗  -->
    <!--  删除分类  -->
    <a-modal :visible="isShowDelModal" width="400px" :mask-closable="false" unmountOnClose :closable="false">
      <div class="del-modal-message">
        <div class="del-name">{{ delData.contractTypeName }}</div>
        <div class="del-tip">确认删除该类型的合同以及相关的配置吗？</div>
      </div>
      <template #footer>
        <a-button style="width: 92px; background-color: #f2f3f5" @click="handleDelCancel">取消</a-button>
        <a-button style="width: 92px" type="primary" @click="handleDelOk">确定</a-button>
      </template>
    </a-modal>

    <!--   新增关联模板 start  -->
    <a-modal :visible="isShowAddProtocolModal" width="486px" unmount-on-close :mask-closable="false" :closable="false">
      <CustomTitle title="关联合同模板" />
      <div class="add-modal-form">
        <div class="custom-form">
          <div class="custom-form-label">合同模板名称</div>
          <a-select
            placeholder="请选择"
            v-model="modalProtocolForm.contractTemplateId"
            :show-header-on-empty="true"
            :style="{ border: !modalProtocolForm.isChecked ? 0 : '1px solid red' }"
            @change="handleSelectProtocol"
          >
            <template #header>
              <div class="search-select-container">
                <a-input
                  v-autoFocus
                  style="border: 0"
                  placeholder="请输入关键词"
                  v-model="keyword"
                  @press-enter="handleSearchField"
                />
                <GiSvgIcon
                  name="searchBox-icon"
                  size="24"
                  style="margin-right: 18px; cursor: pointer"
                  @click="handleSearchField"
                />
              </div>
            </template>
            <a-option v-for="optItem in protocolList" :value="optItem.templateId" :key="optItem.fieldExtendId"
            >{{ optItem.templateName }}
            </a-option>
          </a-select>
        </div>
        <!--        <a-form :model="modalProtocolForm" auto-label-width ref="modalProtocolFormRef" @submit.prevent>-->
        <!--          <a-form-item field="contractTemplateId" label="合同模板名称" :rules="[{ required: true, message: '请选择合同模板' }]">-->
        <!--            <a-select placeholder="请选择" v-model="modalProtocolForm.contractTemplateId" :show-header-on-empty="true">-->
        <!--              <template #header>-->
        <!--                <div class="search-select-container">-->
        <!--                  <a-input-->
        <!--                    v-autoFocus-->
        <!--                    style="border: 0"-->
        <!--                    placeholder="请输入关键词"-->
        <!--                    v-model="keyword"-->
        <!--                    @press-enter="handleSearchField"-->
        <!--                  />-->
        <!--                  <GiSvgIcon-->
        <!--                    name="searchBox-icon"-->
        <!--                    size="24"-->
        <!--                    style="margin-right: 18px; cursor: pointer"-->
        <!--                    @click="handleSearchField"-->
        <!--                  />-->
        <!--                </div>-->
        <!--              </template>-->
        <!--              <a-option v-for="optItem in protocolList" :value="optItem.templateId" :key="optItem.fieldExtendId">{{-->
        <!--                optItem.templateName-->
        <!--              }}</a-option>-->
        <!--            </a-select>-->
        <!--          </a-form-item>-->
        <!--        </a-form>-->
      </div>
      <template #footer>
        <a-button style="width: 92px; background-color: #f2f3f5" @click="handleProtocolCancel">取消</a-button>
        <a-button style="width: 92px" type="primary" @click="handleProtocolOk">确定</a-button>
      </template>
    </a-modal>
    <!--   新增关联模板 end -->

    <!--  设置收款计划 start  -->
    <a-drawer :visible="isShowPaymentPlan" :render-to-body="false" :width="800" :header="false" unmountOnClose>
      <div class="payment-plan-drawer" v-if="isShowPaymentPlan">
        <CustomTitle title="设置收款计划" />
        <div class="payment-plan-header">
          <a-radio-group v-model="paymentPlanForm.receiveType" @change="handelChangeReceiveType">
            <a-radio :value="1">业务类型</a-radio>
            <a-radio :value="2">任务模板</a-radio>
          </a-radio-group>
          <a-button
            type="text"
            @click="handelAddBusinessType"
            v-if="receiveBusTypeLists.length && paymentPlanForm.receiveType === 1"
          >
            <template #icon>
              <icon-plus-circle-fill />
            </template>
            添加业务类型
          </a-button>
        </div>
        <div class="payment-plan-body">
          <template v-if="receiveBusTypeLists.length">
            <div
              class="payment-plan-item"
              v-for="(item, index) in receiveBusTypeLists"
              :style="{ border: item.isNodeListChecked ? '1px solid red' : '1px solid #E1E6ED' }"
            >
              <div class="search-select-label">
                <div class="label">{{ paymentPlanForm.receiveType === 1 ? "添加业务类型" : "添加任务模板" }}</div>
                <a-select
                  :style="{ border: !item.isChecked ? 0 : '1px solid red', width: '80%' }"
                  placeholder="请选择"
                  v-model="item.receiveBusTypeId"
                  :show-header-on-empty="true"
                  @change="handelChangeBusinessType($event, item)"
                >
                  <template #header>
                    <div class="search-select-container">
                      <a-input
                        v-autoFocus
                        style="border: 0"
                        placeholder="请输入关键词"
                        v-model="item.keyword"
                        @press-enter="handleSearchSelect(item)"
                      />
                      <GiSvgIcon
                        name="searchBox-icon"
                        size="24"
                        style="margin-right: 18px; cursor: pointer"
                        @click="handleSearchSelect(item)"
                      />
                    </div>
                  </template>
                  <a-option v-for="optItem in item.selectList" :value="optItem.typeId" :key="optItem.typeId"
                  >{{ optItem.typeName }}
                  </a-option>
                </a-select>
                <GiSvgIcon name="rectification-del" size="16" @click="handelDelBusinessType(index)" />
              </div>
              <!--          任务节点 start    -->
              <div class="payment-plan-table">
                <a-table
                  :data="item.nodeList"
                  :columns="setNodeColumns as any"
                  :pagination="false"
                  :stripe="true"
                  @change="handleChange($event, item)"
                  :draggable="{ type: 'handle' }"
                  :scroll="{ y: '100%' }"
                >
                  <template #receiveTaskName="{ record }">
                    <div class="">
                      <a-select
                        placeholder="请选择"
                        v-model="record.receiveTaskId"
                        @change="handleChangeReceiveTask($event, record, item.nodeList)"
                        :show-header-on-empty="true"
                      >
                        <template #header>
                          <div class="search-select-container">
                            <a-input
                              v-autoFocus
                              style="border: 0"
                              placeholder="请输入关键词"
                              v-model="record.keyword"
                              @press-enter="handleSearchNodeSelect(item, record)"
                            />
                            <GiSvgIcon
                              name="searchBox-icon"
                              size="24"
                              style="margin-right: 18px; cursor: pointer"
                              @click="handleSearchNodeSelect(item, record)"
                            />
                          </div>
                        </template>
                        <a-option v-for="optItem in record.selectList" :value="optItem.receiveTaskId" :key="optItem.receiveTaskId"
                        >{{ optItem.receiveTaskName }}
                        </a-option>
                      </a-select>
                    </div>
                  </template>
                  <template #checkName="{ record }">
                    <div v-if="record.checkName">{{ record.checkName }}</div>
                    <div v-else>--</div>
                  </template>
                  <template #receiveTaskScale="{ record }">
                    <a-input
                      v-model="record.receiveTaskScale"
                      placeholder="支付比例"
                      @blur="handleBlurReceiveTaskScale($event, record, item.nodeList)"
                    />
                  </template>
                  <template #receiveTaskRemark="{ record }">
                    <a-input
                      v-model="record.receiveTaskRemark"
                      placeholder="备注"
                      max-length="100"
                      show-word-limit
                      @blur="handleBlurReceiveTaskScale($event, record, item.nodeList)"
                    />
                  </template>
                  <template #option="{ rowIndex }">
                    <a-button type="text" @click="handelDelTaskNode(item, rowIndex)">移除</a-button>
                  </template>
                </a-table>
                <div class="add-task-node">
                  <a-button type="text" @click="handelAddTaskNode(item)">
                    <template #icon>
                      <icon-plus-circle-fill />
                    </template>
                    任务节点
                  </a-button>
                </div>
              </div>
              <!--           任务节点 end   -->
            </div>
          </template>
          <CustomEmpty v-else>
            <template #default>
              <div class="template-list-button">
                <a-button type="primary" @click="handelAddBusinessType"
                >{{ paymentPlanForm.receiveType === 1 ? "添加业务类型" : "添加任务模板" }}
                </a-button>
              </div>
            </template>
          </CustomEmpty>
        </div>
      </div>
      <template #footer>
        <div class="payment-plan-footer">
          <a-button style="width: 92px; background-color: #f2f3f5" type="secondary" @click="handelClosePaymentPlan"
          >取消
          </a-button>
          <a-button style="width: 92px; margin-left: 16px" type="primary" :loading="isSubmit" @click="handelSubmitPaymentPlanOk"
          >确定
          </a-button>
        </div>
      </template>
    </a-drawer>
    <!--   设置收款计划 end -->
  </div>
</template>

<script setup lang="ts">
import { ref, getCurrentInstance } from "vue";
import { Message } from "@arco-design/web-vue";
import _ from "lodash";
import CustomTitle from "@/components/CustomTitle/index.vue";
import CustomEmpty from "./components/customEmpty/index.vue";
import { initPaymentPlanForm } from "./config";
import {
  contractTypeList,
  addContractType,
  delContractType,
  contractTypeDetail,
  budgetTemplateList,
  delContractTypeProtocol,
  contractTemplateList,
  addContractTypeProtocol,
  searchBusinessType,
  searchBusinessTypeTask,
  sortBusinessTypeTask,
  createPaymentPlan,
  paymentPlanDetail
} from "@/apis";
import type {
  ContractTypeDetail,
  ContractTypeList,
  ContractTemplateItem,
  OfferTemplateItem,
  ProtocolTemplateItem,
  ReceiveBusTypeItem
} from "@/apis";

const { proxy } = getCurrentInstance();
const signingMethod = ref(1);
const isVerify = ref();
const precondition = ref();
const paymentRatio = ref();
/**
 * 切换tab
 */
const activeTabKey = ref("");
const handelTabClick = (e: any) => {
  activeTabKey.value = e;
  getContractTypeDetail(e);
};

/**
 * 合同类型
 */
const contractTypes = ref<ContractTypeList[]>([]);
const getContractTypes = async () => {
  const { data } = await contractTypeList();
  contractTypes.value = data ?? [];
  activeTabKey.value = data?.[0]?.contractTypeId;
  data?.length && getContractTypeDetail(data[0].contractTypeId);
};
const handelAddType = () => {
  isShowAddModal.value = true;
};
const handelDelType = (item: any, index: number) => {
  delData.value = { ...item };
  delItemIndex.value = index;
  isShowDelModal.value = true;
};

/**
 * 合同类型详情
 */
const offerTemplateList = ref<OfferTemplateItem[]>([]);
const protocolTemplateList = ref<ProtocolTemplateItem[]>([]);
const receiveBusTypeList = ref<ReceiveBusTypeItem[]>([]);
const handelDetailData = (data: ContractTypeDetail) => {
  protocolTemplateList.value = data?.protocolTemplateList ?? [];
  receiveBusTypeList.value = data?.receiveBusTypeList ?? [];
  signingMethod.value = data?.signingMethod ?? 1;
  isVerify.value = data.isVerify;
  precondition.value = data.precondition;
  paymentRatio.value = data.paymentRatio;
};
const getContractTypeDetail = async (contractTypeId: string) => {
  const { data } = await contractTypeDetail(contractTypeId);
  handelDetailData(data);
  getBudgetTemplateList(contractTypeId);
};
const getBudgetTemplateList = async (contractTypeId: string) => {
  const { data } = await budgetTemplateList(contractTypeId);
  offerTemplateList.value = data || [];
};

/**
 * 新增合同类型
 */
const isShowAddModal = ref(false);
const modalForm = ref({
  contractTypeId: "",
  contractTypeName: "",
  signingMethod: 1,
  isVerify: 1,
  precondition: 1,
  paymentRatio: null
});
const validateNumber = (value, cb) => {
  const reg = /^\d{1,2}(\.\d{1,2})?$/;
  if (reg.test(value)) {
    if (value <= 0) {
      cb("收款比例必须大于0");
    } else {
      cb();
    }
  } else {
    cb("最多两位整数或者两位整数两位小数");
  }
};
const modalFormRules = {
  contractTypeName: [
    { required: true, message: "请输入合同类型名称", trigger: "blur" },
    { maxLength: 64, message: "请输入64个字符以内", trigger: "blur" }
  ],
  signingMethod: [{ required: true, message: "请选择", trigger: "blur" }],
  isVerify: [{ required: true, message: "请选择", trigger: "blur" }],
  precondition: [{ required: true, message: "请选择进行核量的条件", trigger: "blur" }],
  paymentRatio: [{ required: true, message: "请输入收款比例", trigger: "blur" }, { validator: validateNumber }]
};

const handleAddModalOk = async () => {
  const valid = await proxy.$refs.modalFormRef?.validate();
  if (valid) return;
  await addContractType({ ...modalForm.value });
  Message.success("新建分类成功！");
  getContractTypes();
  handleAddModalCancel();
};
const handleAddModalCancel = async () => {
  await nextTick();
  proxy.$refs.modalFormRef?.resetFields();
  modalForm.value = {
    contractTypeId: "",
    contractTypeName: "",
    signingMethod: 1,
    isVerify: 1,
    precondition: 1,
    paymentRatio: null
  };
  isShowAddModal.value = false;
};

/**
 * 删除合同类型
 */
const isShowDelModal = ref(false);
const delData = ref({}) as any;
const delItemIndex = ref(-1);
const handleDelCancel = () => {
  isShowDelModal.value = false;
  delData.value = {};
  activeTabKey.value = "";
  delItemIndex.value = -1;
};
const handleDelOk = async () => {
  await delContractType(delData.value.contractTypeId);
  Message.success("删除成功");
  // delItemIndex.value !== -1 ? contractTypes.value.splice(delItemIndex.value, 1) : getContractTypes();
  contractTypes.value.splice(delItemIndex.value, 1);
  getContractTypes();
  handleDelCancel();
};

/**
 * 新增关联协议模板
 */
const isShowAddProtocolModal = ref(false);
const modalProtocolForm = ref({
  contractTemplateId: "",
  isChecked: false
});
const keyword = ref("");
const protocolList = ref<ContractTemplateItem[]>([]);
const handelAddProtocol = () => {
  if (!activeTabKey.value) {
    return Message.error("请先选择合同类型");
  }
  isShowAddProtocolModal.value = true;
};
const getProtocolList = async () => {
  const { data } = await contractTemplateList({
    name: keyword.value,
    status: true
  });
  protocolList.value = data ?? [];
};
const handleSearchField = _.debounce(getProtocolList, 500);
const handleSelectProtocol = () => {
  modalProtocolForm.value.isChecked = false;
};
const handleProtocolOk = async () => {
  // const valid = await proxy.$refs.modalProtocolFormRef?.validate();
  // if (valid) return;
  if (!modalProtocolForm.value.contractTemplateId) {
    modalProtocolForm.value.isChecked = true;
    return Message.error("请选择协议模板");
  }
  await addContractTypeProtocol(activeTabKey.value, modalProtocolForm.value.contractTemplateId);
  Message.success("协议模板关联成功！");
  getContractTypeDetail(activeTabKey.value);
  handleProtocolCancel();
};
const handleProtocolCancel = async () => {
  // await nextTick();
  // proxy.$refs.modalProtocolFormRef?.resetFields();
  modalProtocolForm.value = { contractTemplateId: "", isChecked: false };
  isShowAddProtocolModal.value = false;
};

/**
 * 删除关联协议
 */
const handelDelProtocol = async (protocolId: string) => {
  await delContractTypeProtocol(protocolId);
  Message.success("删除成功");
  getContractTypes();
};

/**
 * 收款计划列表
 */
const nodeColumns = [
  {
    title: "任务节点",
    slotName: "receiveTaskName",
    dataIndex: "receiveTaskName",
    align: "center",
    ellipsis: true,
    tooltip: { position: "top" },
    width: 80
  },
  { title: "验收节点", slotName: "checkName", align: "center" },
  { title: "支付比例", slotName: "receiveTaskScale", align: "center" },
  {
    title: "备注",
    dataIndex: "receiveTaskRemark",
    ellipsis: true,
    tooltip: { position: "top" },
    width: 100
  }
];

/**
 * 设置收款计划
 */
const isShowPaymentPlan = ref(false);
const paymentPlanForm = ref({ ...initPaymentPlanForm });
const initNodeList = {
  drag: "contract-drag",
  activeDrag: "contract-drag-active",
  receiveTaskId: "",
  receiveTaskName: "",
  receiveTaskScale: 0,
  receiveTaskRemark: "",
  checkId: "",
  checkName: "--",
  keyword: "",
  selectList: []
};
const initReceiveBusTypeItem = {
  receiveBusTypeId: "",
  receiveBusTypeName: "",
  keyword: "",
  selectList: [],
  nodeList: []
};

const receiveBusTypeLists = ref([]) as any;
const setNodeColumns = [
  // { title: "", slotName: "drag", align: "center", width: 35 },
  { title: "任务节点", slotName: "receiveTaskName", width: 200 },
  { title: "验收节点", slotName: "checkName", width: 120 },
  { title: "支付比例", slotName: "receiveTaskScale", width: 100 },
  { title: "备注", slotName: "receiveTaskRemark", align: "center" },
  { title: "操作", slotName: "option" }
];
// 收款计划详情
const getPaymentPlanDetail = async () => {
  const { data } = await paymentPlanDetail(activeTabKey.value);
  paymentPlanForm.value.receiveType = data.receiveType || 1;
  receiveBusTypeLists.value =
    data.busTypeDetailList?.map((item: any) => {
      if (item.nodeList?.length) {
        item.nodeList = item.nodeList.map((nodeItem: any) => {
          return {
            ...nodeItem,
            receiveTaskScale: Number(nodeItem.receiveTaskScale) ?? 0,
            drag: "contract-drag",
            activeDrag: "contract-drag-active",
            selectList: [
              {
                receiveTaskId: nodeItem.receiveTaskId,
                receiveTaskName: nodeItem.receiveTaskName
              }
            ]
          };
        });
      }
      return {
        ...item,
        selectList: [
          {
            typeId: item.receiveBusTypeId,
            typeName: item.receiveBusTypeName
          }
        ]
      };
    }) || [];
};
const handelShowPaymentPlan = () => {
  if (!activeTabKey.value) {
    return Message.error("请先选择合同类型");
  }
  isShowPaymentPlan.value = true;
  getPaymentPlanDetail();
};
// 收款类型
const handelChangeReceiveType = e => {
  receiveBusTypeLists.value = [];
};
// 添加业务类型
const handelAddBusinessType = () => {
  receiveBusTypeLists.value.push(_.cloneDeep(initReceiveBusTypeItem));
};
// 搜索业务类型
const getBusinessTypeList = async (item: any) => {
  const { data } = await searchBusinessType({
    type: paymentPlanForm.value.receiveType,
    name: item.keyword
  });
  item.selectList = data ?? [];
};
const handleSearchSelect = _.debounce(function (item: any) {
  getBusinessTypeList(item);
}, 500);
// 选择业务类型
//TODO:后续优化
const handelChangeBusinessType = (e: any, item: any) => {
  const list = receiveBusTypeLists.value.filter((i: any) => i.receiveBusTypeId === item.receiveBusTypeId);
  if (list?.length >= 2) {
    item.receiveBusTypeId = "";
    return Message.error("同一个合同下不允许存在多个相同节点！");
  }
  const selectObj = item.selectList.find((item: any) => item.typeId === e);
  !_.isEmpty(selectObj) && (item.receiveBusTypeName = selectObj.typeName);
  item.isChecked = false;
  item.nodeList = [];
};
// 删除业务类型
const handelDelBusinessType = (index: number) => {
  receiveBusTypeLists.value.splice(index, 1);
};
// 添加任务节点任务
const handelAddTaskNode = (item: any) => {
  if (!item.receiveBusTypeId) {
    item.isChecked = true;
    return Message.error(`请先选择${paymentPlanForm.value.receiveType === 1 ? "业务类型" : "任务模板"}`);
  }
  item.nodeList.push(_.cloneDeep(initNodeList));
};
// 搜索节点任务
const getBusinessTypeTask = async (parentItem: any, nodeItem: any) => {
  const params = {
    type: paymentPlanForm.value.receiveType,
    typeId: parentItem.receiveBusTypeId,
    name: nodeItem.keyword
  };
  const { data } = await searchBusinessTypeTask(params);
  if (nodeItem.receiveTaskId) {
    nodeItem.receiveTaskName = data.find(item => item.receiveTaskId === nodeItem.receiveTaskId)?.receiveTaskName;
  }
  nodeItem.selectList = data ?? [];
};
const handleSearchNodeSelect = _.debounce(function (parentItem: any, nodeItem: any) {
  getBusinessTypeTask(parentItem, nodeItem);
}, 500);
// 选择节点任务
//TODO:后续优化
const handleChangeReceiveTask = (e: any, nodeItem: any, nodeList: any) => {
  // 是否重复
  const list = nodeList.filter((item: any) => item.receiveTaskId === nodeItem.receiveTaskId);
  if (list?.length >= 2) {
    nodeItem.receiveTaskId = "";
    nodeItem.receiveTaskName = "";
    return Message.error("同一个合同下不允许存在多个相同节点！");
  }
  const selectObj = nodeItem.selectList.find((item: any) => item.receiveTaskId === e);
  if (!_.isEmpty(selectObj)) {
    nodeItem.receiveTaskName = selectObj.receiveTaskName;
    nodeItem.receiveTaskScale = selectObj.receiveTaskScale;
    nodeItem.checkId = selectObj.checkId;
    nodeItem.checkName = selectObj.checkName;
  }
};
// 删除任务节点
const handelDelTaskNode = (item: any, index: number) => {
  item.nodeList.splice(index, 1);
};
// 任务节点排序
const handleChange = async (e: any, item: any) => {
  const ids = e.map((item: any) => item.receiveTaskId);
  await sortBusinessTypeTask(ids);
  Message.success("操作成功");
  item.nodeList = [...e];
};
// 支付比例
const handleBlurReceiveTaskScale = (e: any, nodeItem: any, nodeList: any) => {
  // const reg = /^\d+(?=\.{0,1}\d+$|$)/;
  // if (!reg.test(nodeItem.receiveTaskScale)) {
  //   nodeItem.receiveTaskScale = 0;
  //   return Message.error("请输入0-100的整数或小数");
  // }
  // const receiveTaskScale = nodeItem.receiveTaskScale;
  // if (receiveTaskScale < 0 || receiveTaskScale > 100) {
  //   nodeItem.receiveTaskScale = 0;
  //   return Message.error("支付比例不能小于0或大于100");
  // }
  // const sum =
  //   nodeList?.reduce((pre: any, cur: any) => {
  //     return pre + Number(cur.receiveTaskScale);
  //   }, 0) || 0;
  // if (sum > 100) {
  //   nodeItem.receiveTaskScale = 0;
  //   Message.error("单个业务类型支付比例相加要等于100%，请检查！");
  // }
};
/**
 * 校验支付比例
 */
const blurReceiveTaskScaleCheck = (nodeList: any) => {
  const reg = /^\d+(?=\.{0,1}\d+$|$)/;
  const sum =
    nodeList?.reduce((pre: any, cur: any) => {
      return pre + Number(cur.receiveTaskScale);
    }, 0) || 0;
  let resultObj = { result: true, msg: "" };
  nodeList?.some((nodeItem: any) => {
    if (!reg.test(nodeItem.receiveTaskScale)) {
      resultObj.result = false;
      resultObj.msg = "请输入0-100的整数或小数";
      return true;
    }
    const receiveTaskScale = nodeItem.receiveTaskScale;
    if (receiveTaskScale < 0 || receiveTaskScale > 100) {
      resultObj.result = false;
      resultObj.msg = "支付比例不能小于0或大于100";
      return true;
    }
    if (sum > 100 || sum < 100) {
      resultObj.result = false;
      resultObj.msg = "单个业务类型支付比例相加要等于100%，请检查！";
      return true;
    }
  });
  return { ...resultObj };
};
/**
 * 校验提交数据
 */
const blurReceiveTaskScaleCheckAll = () => {
  return receiveBusTypeLists.value?.some((item: any) => {
    item.isNodeListChecked = false;
    item.isChecked = false;
    if (!item.receiveBusTypeId) {
      item.isChecked = true;
      const passMessage = paymentPlanForm.value.receiveType === 1 ? "业务类型不能为空！" : "任务模板不能为空！";
      Message.error(passMessage);
      return true;
    }
    if (!item.nodeList?.length) {
      item.isNodeListChecked = true;
      Message.error("任务节点不能为空！");
      return true;
    }
    if (item.nodeList?.length) {
      const checkResult = blurReceiveTaskScaleCheck(item.nodeList);
      if (!checkResult.result) {
        item.isNodeListChecked = true;
        Message.error(checkResult.msg);
        return true;
      }
    }
  });
};

/**
 * 提交
 */
const isSubmit = ref(false);
const submitPaymentPlan = async () => {
  try {
    isSubmit.value = true;
    if (!receiveBusTypeLists.value?.length) {
      isSubmit.value = false;
      return Message.error("请填写数据后提交！");
    }
    if (blurReceiveTaskScaleCheckAll()) return (isSubmit.value = false);
    const postData = _.cloneDeep(paymentPlanForm.value);
    postData.receiveBusTypeList = _.cloneDeep(receiveBusTypeLists.value);
    postData.contractTypeId = activeTabKey.value;
    await createPaymentPlan(postData);
    Message.success("操作成功");
    isSubmit.value = false;
    getContractTypes();
    handelClosePaymentPlan();
  } catch (err) {
    isSubmit.value = false;
  }
};
const handelSubmitPaymentPlanOk = _.debounce(submitPaymentPlan, 500);
const handelClosePaymentPlan = () => {
  isShowPaymentPlan.value = false;
  paymentPlanForm.value = _.cloneDeep(initPaymentPlanForm);
  receiveBusTypeLists.value = [];
};

getContractTypes();
</script>

<style scoped lang="scss">
@import "contractConfig";

:deep(.contract-config-body .template-item .agreement-template-item) {
  font-size: 14px;
  color: #007dff;
  line-height: 22px;
  cursor: pointer;
}
</style>
<style lang="scss">
// 拖拽图标
.arco-table-td.arco-table-operation.arco-table-drag-handle {
  svg {
    display: none;
  }

  &:hover {
    cursor: pointer;
  }

  .arco-table-cell {
    &::after {
      content: "";
      display: inline-block;
      width: 18px;
      height: 18px;
      background: url("@/assets/images/contract-drag.png") no-repeat center;
      background-size: 18px;
    }
  }
}

//
.arco-table-tr.arco-table-tr-drag {
  .arco-table-td.arco-table-operation.arco-table-drag-handle {
    .arco-table-cell::after {
      content: "";
      display: inline-block;
      width: 18px;
      height: 18px;
      background: url("@/assets/images/contract-drag-active.png") no-repeat center;
      background-size: 18px;
    }
  }
}
</style>
